package com.feeyo.groundservice.base_util.upgrade

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.webkit.MimeTypeMap
import androidx.core.content.FileProvider
import com.feeyo.groundservice.base_util.toast
import java.io.File

object AppInstallUtil {

    //安装apk
    fun installApkNew(context: Context, path: String) {
        val file = File(path)
        if (!file.exists()) {
            toast("安装包文件未能找到")
            return
        }
        val intent = Intent()
        //执行动作
        intent.action = Intent.ACTION_VIEW
        //执行的数据类型
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            val uri =
                FileProvider.getUriForFile(context, context.packageName + ".FileProvider", file)
            intent.setDataAndType(uri, context.contentResolver.getType(uri))
        } else {
            intent.setDataAndType(Uri.fromFile(file), getMIMEType(file))
        }
        try {
            context.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    private fun getMIMEType(var0: File): String? {
        val var1: String?
        val var2 = var0.name
        val var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length).lowercase()
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3)
        return var1
    }
}